package jnpf.base.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.entity.*;
import jnpf.base.mapper.ModuleMapper;
import jnpf.base.model.module.ModuleExportModel;
import jnpf.base.service.*;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.util.*;
import jnpf.util.context.SpringContext;
import jnpf.util.enums.ModuleTypeEnum;
import jnpf.util.file.FileExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统功能
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Service
public class ModuleServiceImpl extends ServiceImpl<ModuleMapper, ModuleEntity> implements ModuleService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ModuleButtonService moduleButtonService;
    @Autowired
    private ModuleColumnService moduleColumnService;
    @Autowired
    private ModuleDataAuthorizeService moduleDataAuthorizeService;
    @Autowired
    private ModuleButtonService buttonService;
    @Autowired
    private ModuleColumnService columnService;
    @Autowired
    private ModuleFormService formService;
    @Autowired
    private ModuleDataAuthorizeSchemeService schemeService;
    @Autowired
    private ModuleDataAuthorizeService authorizeService;
    @Autowired
    private FileExport fileExport;
    @Autowired
    private ConfigValueUtil configValueUtil;

    @Override
    public List<ModuleEntity> getList() {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(ModuleEntity::getSortCode)
                .orderByDesc(ModuleEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<ModuleEntity> getList(List<String> list) {
        if (list.size() == 0) {
            return new ArrayList<>(16);
        }
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(ModuleEntity::getSystemId, list);
        queryWrapper.lambda().eq(ModuleEntity::getEnabledMark, 1);
        queryWrapper.lambda().orderByAsc(ModuleEntity::getSortCode)
                .orderByDesc(ModuleEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<ModuleEntity> getList(String systemId, String category, String keyword, String type, String enabledMark, String parentId) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        // 根据系统id获取功能
//        if ("0".equals(systemId)) {
////            queryWrapper.lambda().eq(ModuleEntity::getSystemId, userProvider.get().getSystemId());
//        } else
        if (!"0".equals(systemId)) {
            queryWrapper.lambda().eq(ModuleEntity::getSystemId, systemId);
        }
        if (!StringUtil.isEmpty(category)) {
            flag = true;
            queryWrapper.lambda().eq(ModuleEntity::getCategory, category);
        }
        if (!StringUtil.isEmpty(keyword)) {
            flag = true;
            queryWrapper.lambda().and(t -> t.like(ModuleEntity::getFullName, keyword));
        }
        if (StringUtil.isNotEmpty(type)) {
            flag = true;
            queryWrapper.lambda().eq(ModuleEntity::getType, Integer.valueOf(type));
        }
        if (StringUtil.isNotEmpty(enabledMark)) {
            queryWrapper.lambda().eq(ModuleEntity::getEnabledMark, Integer.valueOf(enabledMark));
        }
        if (StringUtil.isNotEmpty(parentId)) {
            flag = true;
            queryWrapper.lambda().eq(ModuleEntity::getParentId, parentId);
        }
        queryWrapper.lambda().orderByAsc(ModuleEntity::getSortCode)
                .orderByDesc(ModuleEntity::getCreatorTime);
        if (flag) {
            queryWrapper.lambda().orderByDesc(ModuleEntity::getLastModifyTime);
        }
        return this.list(queryWrapper);
    }

    @Override
    public List<ModuleEntity> getList(String id) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getParentId, id);
        queryWrapper.lambda().orderByAsc(ModuleEntity::getSortCode)
                .orderByDesc(ModuleEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public ModuleEntity getInfo(String id) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public ModuleEntity getInfo(String id, String systemId) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getId, id);
        queryWrapper.lambda().eq(ModuleEntity::getSystemId, systemId);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<ModuleEntity> getInfoByFullName(String fullName, String systemId) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getFullName, fullName);
        queryWrapper.lambda().eq(ModuleEntity::getSystemId, systemId);
        return this.list(queryWrapper);
    }

    @Override
    public ModuleEntity getInfo(String id, String systemId, String parentId) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getId, id);
        queryWrapper.lambda().eq(ModuleEntity::getSystemId, systemId);
        queryWrapper.lambda().eq(ModuleEntity::getParentId, parentId);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean isExistByFullName(ModuleEntity entity, String category, String systemId) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getFullName, entity.getFullName()).eq(ModuleEntity::getCategory, category);
        if (!StringUtil.isEmpty(entity.getId())) {
            queryWrapper.lambda().ne(ModuleEntity::getId, entity.getId());
        }

        // 通过系统id查询
        queryWrapper.lambda().eq(ModuleEntity::getSystemId, systemId);

        List<ModuleEntity> entityList = this.list(queryWrapper);
        if (entityList.size() > 0) {
            for (ModuleEntity moduleEntity : entityList) {
                if (moduleEntity.getParentId().equals(entity.getParentId())) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean isExistByEnCode(ModuleEntity entity, String category, String systemId) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getEnCode, entity.getEnCode()).eq(ModuleEntity::getCategory, category);
        if (!StringUtil.isEmpty(entity.getId())) {
            queryWrapper.lambda().ne(ModuleEntity::getId, entity.getId());
        }

        List<ModuleEntity> entityList = this.list(queryWrapper);
        if (entityList.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    @DSTransactional
    @Override
    public void delete(ModuleEntity entity) {
        this.removeById(entity.getId());
        QueryWrapper<ModuleButtonEntity> buttonWrapper = new QueryWrapper<>();
        buttonWrapper.lambda().eq(ModuleButtonEntity::getModuleId, entity.getId());
        moduleButtonService.remove(buttonWrapper);
        QueryWrapper<ModuleColumnEntity> columnWrapper = new QueryWrapper<>();
        columnWrapper.lambda().eq(ModuleColumnEntity::getModuleId, entity.getId());
        moduleColumnService.remove(columnWrapper);
        QueryWrapper<ModuleDataAuthorizeEntity> dataWrapper = new QueryWrapper<>();
        dataWrapper.lambda().eq(ModuleDataAuthorizeEntity::getModuleId, entity.getId());
        moduleDataAuthorizeService.remove(dataWrapper);
        Object service = SpringContext.getBean("appDataServiceImpl");
        Class[] types = new Class[]{String.class};
        Object[] datas = new Object[]{entity.getId()};
        ReflectionUtil.invokeMethod(service, "delete", types, datas);
    }

    @Override
    public void deleteBySystemId(String systemId) {
        QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModuleEntity::getSystemId, systemId);
        this.remove(queryWrapper);
    }

    @DSTransactional
    @Override
    public void deleteModule(ModuleEntity entity) {
        QueryWrapper<ModuleButtonEntity> buttonWrapper = new QueryWrapper<>();
        buttonWrapper.lambda().eq(ModuleButtonEntity::getModuleId, entity.getId());
        moduleButtonService.remove(buttonWrapper);
        QueryWrapper<ModuleColumnEntity> columnWrapper = new QueryWrapper<>();
        columnWrapper.lambda().eq(ModuleColumnEntity::getModuleId, entity.getId());
        moduleColumnService.remove(columnWrapper);
        QueryWrapper<ModuleFormEntity> formWrapper = new QueryWrapper<>();
        formWrapper.lambda().eq(ModuleFormEntity::getModuleId, entity.getId());
        formService.remove(formWrapper);
    }

    @DSTransactional
    @Override
    public void create(ModuleEntity entity) {
//        boolean flag = false;
//        if (entity.getId() == null) {
            entity.setId(RandomUtil.uuId());
//            flag = true;
//        }
        this.save(entity);
        //添加默认按钮
        if ("3".equals(String.valueOf(entity.getType()))) {
//            Map<String,Object> propJsonMap= JSONUtil.StringToMap(entity.getPropertyJson());
//            if(propJsonMap!=null){
//                VisualdevEntity visualdevEntity =visualdevService.getInfo(propJsonMap.get("moduleId").toString());
//                //去除模板中的F_
//                visualdevEntity= VisualUtil.delFKey(visualdevEntity);
//                if(visualdevEntity!=null){
//                    List<BtnData> btnData =new ArrayList<>();
//                    Map<String,Object> column=JSONUtil.StringToMap(visualdevEntity.getColumnData());
//                    if(column.get("columnBtnsList")!=null){
//                        btnData.addAll(JSONUtil.getJsonToList(JSONUtil.getJsonToListMap(column.get("columnBtnsList").toString()),BtnData.class));
//                    }
//                    if(column.get("btnsList")!=null){
//                        btnData.addAll(JSONUtil.getJsonToList(JSONUtil.getJsonToListMap(column.get("btnsList").toString()),BtnData.class));
//                    }
//                    if(btnData.size()>0){
//                        for(BtnData btn:btnData){
//                            ModuleButtonEntity moduleButtonEntity=new ModuleButtonEntity();
//                            moduleButtonEntity.setId(RandomUtil.uuId());
//                            moduleButtonEntity.setParentId("-1");
//                            moduleButtonEntity.setFullName(btn.getLabel());
//                            moduleButtonEntity.setEnCode("btn_"+btn.getValue());
//                            moduleButtonEntity.setSortCode(0L);
//                            moduleButtonEntity.setModuleId(entity.getId());
//                            moduleButtonEntity.setEnabledMark(1);
//                            moduleButtonEntity.setIcon(btn.getIcon());
//                            moduleButtonService.save(moduleButtonEntity);
//                        }
//                    }
//                    List<IndexGridField6Model> indexGridField6Models =new ArrayList<>();
//                    if(column.get("columnList")!=null){
//                        indexGridField6Models.addAll(JSONUtil.getJsonToList(JSONUtil.getJsonToListMap(column.get("columnList").toString()),IndexGridField6Model.class));
//                       if(indexGridField6Models.size()>0){
//                           for(IndexGridField6Model field6Model:indexGridField6Models){
//                               ModuleColumnEntity moduleColumnEntity=new ModuleColumnEntity();
//                               moduleColumnEntity.setId(RandomUtil.uuId());
//                               moduleColumnEntity.setParentId("-1");
//                               moduleColumnEntity.setFullName(field6Model.getLabel());
//                               moduleColumnEntity.setEnCode(field6Model.getProp());
//                               moduleColumnEntity.setSortCode(0L);
//                               moduleColumnEntity.setModuleId(entity.getId());
//                               moduleColumnEntity.setEnabledMark(1);
//                               moduleColumnService.save(moduleColumnEntity);
//                           }
//                       }
//                    }
//                }
//            }
        } else if ("4".equals(String.valueOf(entity.getType()))) {
            for (int i = 0; i < 3; i++) {
                String fullName = "新增";
                String value = "add";
                String icon = "el-icon-plus";
                if (i == 1) {
                    fullName = "编辑";
                    value = "edit";
                    icon = "el-icon-edit";
                }
                if (i == 2) {
                    fullName = "删除";
                    value = "remove";
                    icon = "el-icon-delete";
                }
                ModuleButtonEntity moduleButtonEntity = new ModuleButtonEntity();
                moduleButtonEntity.setId(RandomUtil.uuId());
                moduleButtonEntity.setParentId("-1");
                moduleButtonEntity.setFullName(fullName);
                moduleButtonEntity.setEnCode("btn_" + value);
                moduleButtonEntity.setSortCode(0L);
                moduleButtonEntity.setModuleId(entity.getId());
                moduleButtonEntity.setEnabledMark(1);
                moduleButtonEntity.setIcon(icon);
                moduleButtonService.save(moduleButtonEntity);
            }

        }
    }

    @Override
    public boolean update(String id, ModuleEntity entity) {
        entity.setId(id);
        entity.setLastModifyTime(DateUtil.getNowDate());
        return this.updateById(entity);
    }

    @Override
    public DownloadVO exportData(String id) {
        //获取信息转model
        ModuleEntity moduleEntity = getInfo(id);
        List<ModuleButtonEntity> buttonServiceList = buttonService.getList(id);
        List<ModuleColumnEntity> columnServiceList = columnService.getList(id);
        List<ModuleDataAuthorizeSchemeEntity> schemeServiceList = schemeService.getList(id);
        List<ModuleDataAuthorizeEntity> authorizeServiceList = authorizeService.getList(id);
        List<ModuleFormEntity> formList = formService.getList(id);
        ModuleExportModel exportModel = new ModuleExportModel();
        exportModel.setModuleEntity(moduleEntity);
        exportModel.setButtonEntityList(buttonServiceList);
        exportModel.setColumnEntityList(columnServiceList);
        exportModel.setFormEntityList(formList);
        exportModel.setSchemeEntityList(schemeServiceList);
        exportModel.setAuthorizeEntityList(authorizeServiceList);
        //导出文件
        DownloadVO downloadVO = fileExport.exportFile(exportModel, configValueUtil.getTemporaryFilePath(), moduleEntity.getFullName(), ModuleTypeEnum.SYSTEM_MODULE.getTableName());
        return downloadVO;
    }

    @Override
    @DSTransactional
    public boolean importData(ModuleExportModel exportModel) throws DataException {
        try {
            boolean isExists = true;
            ModuleEntity moduleEntity = exportModel.getModuleEntity();
            //开始导入
            if (!isExistByFullName(moduleEntity, moduleEntity.getCategory(), moduleEntity.getSystemId())
                    && !isExistByEnCode(moduleEntity, moduleEntity.getCategory(), moduleEntity.getSystemId())) {
                isExists = false;
                create(moduleEntity);
            }
            //按钮
            List<ModuleButtonEntity> buttonEntityList = JsonUtil.getJsonToList(exportModel.getButtonEntityList(), ModuleButtonEntity.class);
            for (ModuleButtonEntity buttonEntity : buttonEntityList) {
                if (buttonService.getInfo(buttonEntity.getId(), moduleEntity.getId()) == null
                        && !buttonService.isExistByFullName(moduleEntity.getId(), buttonEntity.getFullName(), buttonEntity.getId())
                        && !buttonService.isExistByEnCode(moduleEntity.getId(), buttonEntity.getEnCode(), buttonEntity.getId())
                ) {
                    isExists = false;
                    buttonEntity.setModuleId(moduleEntity.getId());
                    buttonService.create(buttonEntity);
                }
            }
            //列表
            List<ModuleColumnEntity> columnEntityList = JsonUtil.getJsonToList(exportModel.getColumnEntityList(), ModuleColumnEntity.class);
            for (ModuleColumnEntity columnEntity : columnEntityList) {
                isExists = false;
                columnEntity.setModuleId(moduleEntity.getId());
                columnService.create(columnEntity);
            }
            //表单
            List<ModuleFormEntity> formEntityList = JsonUtil.getJsonToList(exportModel.getFormEntityList(), ModuleFormEntity.class);
            for (ModuleFormEntity formEntity : formEntityList) {
                isExists = false;
                formEntity.setModuleId(moduleEntity.getId());
                formService.create(formEntity);
            }
            //数据权限
            Map<String, String> authorizeId = new HashMap<>(16);
            List<ModuleDataAuthorizeEntity> authorizeEntityList = JsonUtil.getJsonToList(exportModel.getAuthorizeEntityList(), ModuleDataAuthorizeEntity.class);
            for (ModuleDataAuthorizeEntity authorizeEntity : authorizeEntityList) {
                isExists = false;
                authorizeEntity.setModuleId(moduleEntity.getId());
                // 导入前id
                String id = authorizeEntity.getId();
                authorizeService.create(authorizeEntity);
                authorizeId.put(id, authorizeEntity.getId());
            }
            //数据权限方案
            List<ModuleDataAuthorizeSchemeEntity> schemeEntityList = JsonUtil.getJsonToList(exportModel.getSchemeEntityList(), ModuleDataAuthorizeSchemeEntity.class);
            for (ModuleDataAuthorizeSchemeEntity schemeEntity : schemeEntityList) {
                isExists = false;
                schemeEntity.setModuleId(moduleEntity.getId());
                // 得到条件
                String conditionJson = schemeEntity.getConditionJson();
                if (StringUtil.isNotEmpty(conditionJson)) {
                    for (String oldId : authorizeId.keySet()) {
                        conditionJson = conditionJson.replaceAll(oldId, authorizeId.get(oldId));
                    }
                }
                schemeEntity.setConditionJson(conditionJson);
                schemeService.create(schemeEntity);
            }
            return isExists;
        } catch (Exception e) {
            e.printStackTrace();
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new DataException(e.getMessage());
        }
    }

    @Override
    @DSTransactional
    public List<ModuleEntity> getModuleList(String visualId) {
        QueryWrapper<ModuleEntity> moduleWrapper = new QueryWrapper<>();
        moduleWrapper.lambda().eq(ModuleEntity::getModuleId, visualId);
        return this.list(moduleWrapper);
    }

}
